﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Net;

namespace PTiRouZ.Net.SilverLight.Api
{
    /// <summary>
    /// Class permttant de convertir le code Json en objet .Net
    /// </summary>
    public static class serializeTools
    {
        /// <summary>Déserialise une chaine Json en Object .Net</summary>
        /// <typeparam name="T">Type de l'Objet .Net de sortie</typeparam>
        /// <param name="jsonString">Chaine Json</param>
        /// <returns>un objet .Net de type <typeparamref name="T"/></returns>
        public static T Deserialize<T>(string jsonString)
        {
    //        try {
                using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                    return (T)serializer.ReadObject(ms);
                }
//            } catch (InvalidCastException icex ){
  //          }
        }

        /// <summary>Sérialise un Object .Net en une chaine Json</summary>
        /// <typeparam name="T">Type de l'Objet .Net en entrée</typeparam>
        /// <param name="ClassObject">Object .Net de Type <typeparamref name="T"/></param>
        /// <returns>Une chaine Json</returns>
        public static string Serialize<T>(T ClassObject)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                serializer.WriteObject(ms, ClassObject);
                //return Encoding.Unicode.GetString(ms.ToArray());
                return ms.ToString();
            }
        }
    }
}
